var express = require('express')
var { graphqlHTTP } = require('express-graphql')
const { buildSchema } = require('graphql')

// String, Int, Float, Boolean, ID 
// type 定义的就是 对象
// [类型]  [Int]代表整型数组
/*
    type Query {
        rollDice(numDice: Int!, numSides:Int!): [Int]
    }
*/
var schema = buildSchema(`
  type Account {
    name: String
    age: Int
    sex: String
    department: String
    salary: Int
  }
  input AccountInput {
    name: String
    age: Int
    sex: String
    department: String
    salary: Int
  }
  type Mutation {
    createAccount(input: AccountInput): Account
    updateAccount(id: ID!, input: AccountInput): Account
  }
  type Query {
    accounts: [Account]
  }
`)

const fakeDb = {}

var root = {
  accounts() {
    var arr = []
    for (const key in fakeDb) {
      arr.push(fakeDb[key])
    }
    return arr
  },
  createAccount({ input }) {
    fakeDb[input.name] = input
    return fakeDb[input.name]
  },
  updateAccount({ id, input }) {
    const updatedAccount = Object.assign({}, fakeDb[id], input)
    fakeDb[id] = updatedAccount
    return updatedAccount
  }
}
// 查询语句
/*
{
  getClassMates(classNo:31)
}
*/
var app = express()

/**
 * @type {import('express').RequestHandler}
 */
const authMiddleware = (req, res, next) => {
  if (req.url.indexOf('/graphql') !== -1 && req.headers.cookie.indexOf('auth') === -1) {
    res.send(JSON.stringify({
      error: "您没有权限访问这个接口"
    }))
    return
  }
  next()
}

app.use(authMiddleware)

app.get('/', (req, res) => {
  res.end(`
  <a href="/graphql">graphql</a>
  <script>
    window.onload = function() {
      fetch('/cookie', {
        method: 'post',
        credentials : 'include',
        headers: {
          'Content-Type': 'application/json',
          'Accept': 'application/json'
        },
      }).then(res => res.json())
      .then(json => document.cookie="auth=" + json.cookie)
    }
  </script>
  `)
})

app.post('/cookie', function (req, res) {
  res.json({
    cookie: "cookie"
  })
})

app.use('/graphql', graphqlHTTP({
  schema: schema,
  rootValue: root,
  graphiql: true // 是否开启调试界面，true是开启，false是不开启
}))

app.use(express.static('public'))

app.listen(4000, () => console.log('server is run on http://localhost:4000'))